import tensorflow as tf

# clip_by_value将张量限制在一定范围内
v = tf.constant([[1.0,2.0,3.0],[4.0,5.0,6.0]])
v2 = tf.constant([[1.0,2.0,3.0],[4.0,5.0,6.0]])

print(tf.clip_by_value(v,2.5,4.5))

# 进行log运算
print(tf.log(v).eval())

# 矩阵乘法
print(tf.matmul(v,v2).eval())

# 交叉熵与softmax函数结合
# 模拟输出向量和期望向量
y_ = tf.constant([1])
y = tf.constant([0])
# cosss_entropy = tf.nn.softmax_cross_entropy_with_logits（y,y_)
mse = tf.reduce_mean(tf.square(y_-y))

# a为少卖一个少的利润，b为多生产一个的成本
# 步骤：greater判断哪边较大，再根据较大的选择第二还是第三个参数
loss = tf.reduce_sum(tf.select(tf.greater(v1,v2),(v1-v2)*a,(v2-v1)*b))

from numpy.random import RandomState

batch_size = 8

x = tf.placeholder(tf.float32,shape=(None,2),name='x-input')
y_ = tf.placeholder(tf.float32,shape=(None,1),name='y-input')

w1 = tf.Variable(tf.random_normal([2,1],stddev=1,seed=1))
y = tf.matmul(x,w1)

## 设置损失函数中的权重，此处为预测少损失更大
loss_less = 10
loss_more = 1
loss = tf.reduce_sum(tf.where(tf.greater(y,y_),
                               (y-y_)*loss_more,
                               (y_-y)*loss_less))

train_step = tf.train.AdamOptimizer(0.001).minimize(loss)

rdm = RandomState(1)
dataset_size = 128
X = rdm.rand(dataset_size,2)

# 增加噪音
Y = [[x1+x2+rdm.rand()/10.0-0.05] for (x1,x2) in X]

with tf.Session() as sess:
    init_op = tf.initialize_all_variables()
    sess.run(init_op)
    STEPS = 5000
    for i in range(STEPS):
        start = (i*batch_size)%dataset_size
        end = min(start+batch_size,dataset_size)
        sess.run(train_step,feed_dict={x:X[start:end],y_:Y[start:end]})
        print(sess.run(w1))



